let subs = document.getElementsByClassName('sub')
let adds = document.getElementsByClassName('add')
let storeNum = 5
for (let i = 0; i < subs.length; i++) {
  // sub按钮绑定事件
  subs[i].onclick = function () {
    // this是触发事件的元素对象
    let num = this.nextElementSibling.innerHTML
    num--
    if (num < 1) {
      num = 1
      alert('商品的数量不能小于1')
    }
    this.nextElementSibling.innerHTML = num
    setSumprice(this, num)
  }
}
for (let i = 0; i < adds.length; i++) {
  // add按钮绑定事件
  adds[i].onclick = function () {
    let num = this.previousElementSibling.innerHTML
    num++
    if (num > storeNum) {
      num = storeNum
      alert('商品的数量不能超库存数量')
    }
    this.previousElementSibling.innerHTML = num
    setSumprice(this, num)
  }
}

// 设置总价的方法
function setSumprice(node, num) {
  // 找单价元素price
  let price = node.parentNode.previousElementSibling.innerHTML
  let total = '￥' + (+price.substring(1) * num).toFixed(1)
  // 找总价元素sum-price
  let sumPriceNode = node.parentNode.nextElementSibling
  sumPriceNode.innerHTML = total
}

let buyButton = document.querySelector('.buy')
buyButton.onclick = function () {
  let list = document.querySelectorAll('.box>ul>li')
  let arr = []
  for (let item of list) {
    let object = {}
    let children = item.children // 不是数组是集合没有forEach方法
    Array.from(children).forEach((item) => {
      if (item.className === 'name') {
        object.name = item.innerHTML
      } else if (item.className === 'price') {
        object.price = +item.innerHTML.substring(1)
      } else if (item.className === 'opt') {
        object.num = +item.children[1].innerHTML
      } else if (item.className === 'sum-price') {
        object.sumPrice = +item.innerHTML.substring(1)
      }
    })
    arr.push(object)
  }
  renderInfo(arr)
}

function renderInfo(arr) {
  let str = `您本次购买的商品信息如下:<br />`
  let sum = 0
  for (let item of arr) {
    if (item.name) {
      str += `${item.name}:￥${item.sumPrice}<br />`
      sum += item.sumPrice
    }
  }
  str += `商品共计:￥${sum.toFixed(1)}`
  let info = document.querySelector('.info')
  info.innerHTML = str
  info.style.border = '1px solid red'
  info.style.padding = '10px'
}
